package com.xuzhiguang.baidu.pan.sdk.token;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xuzhiguang.baidu.pan.sdk.exception.BaiduPanSdkException;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;


public class RedisTokenStorage implements ITokenStorage {

    private final String keyPrefix;

    private final JedisPool jedisPool;

    private final static String DEFAULT_KEY_PREFIX = "baidupan_token:";

    private final static long REFRESH_EXPIRES_TIME = 180 * 24 * 60 * 60 * 1000L;

    private final ObjectMapper objectMapper = new ObjectMapper();

    public RedisTokenStorage(JedisPool jedisPool) {
        this(DEFAULT_KEY_PREFIX, jedisPool);
    }

    public RedisTokenStorage(String keyPrefix, JedisPool jedisPool) {
        this.keyPrefix = keyPrefix;
        this.jedisPool = jedisPool;
    }

    @Override
    public void save(String apiKey, AccessToken accessToken) throws BaiduPanSdkException {

        try (Jedis jedis = jedisPool.getResource()) {
            jedis.set(keyPrefix + apiKey, objectMapper.writeValueAsString(accessToken));
        } catch (JsonProcessingException e) {
            throw new BaiduPanSdkException("保存 accessToken 异常", e);
        }
    }

    @Override
    public AccessToken get(String apiKey) throws BaiduPanSdkException {

        try (Jedis jedis = jedisPool.getResource()) {
            String token = jedis.get(keyPrefix + apiKey);
            if (token == null) {
                return null;
            }

            try {
                return objectMapper.readValue(token, AccessToken.class);
            } catch (JsonProcessingException e) {
                throw new BaiduPanSdkException("获取 accessToken 异常", e);
            }
        }
    }

    @Override
    public void delete(String apiKey) {

        try (Jedis jedis = jedisPool.getResource()) {
            jedis.del(keyPrefix + apiKey);
        }

    }
}
